<template>
  <!--Dialog-->
  <Dialog v-model="modelValue">
    <el-form style="width: 99%;" ref="flowForm" label-position="top" :rules="flowRules" :model="formData">
      <el-row :gutter="15" v-for="(row, rowkey) in workflow.inputs" :key="rowkey">
        <el-col v-for="(column, key) in row" :key="key" :span="24 / row.length">
          <WorkflowFormItem v-model="formData[element.name]" :element="column[key]" v-for="(element, key) in column"
            :key="element.id" />
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSavue(flowForm)" :loading="isLoading">保存</el-button>
      <el-button @click="onClose">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { onMounted, computed, ref, defineEmits, defineModel, defineProps, type PropType } from "vue";
import { propTypes } from '@/utils/propTypes';
import { Dialog } from '@/components/dialog/index';
import { ElMessage, type FormInstance } from "element-plus";
import pinia from '@/stores';
import useWorkflowStore from '@/stores/modules/workflow';
import type { ValidateFieldsError } from 'async-validator/dist-types';
import type { WorkflowDefinition, WorkFormComponentsRules } from "@/utils/api/workflow/definition/type";
import WorkflowFormItem from '../create/workflow-form-item.vue';
import { startAsync } from "@/utils/api/workflow/list";
import type { StartWorkflowInput, StartWorkflowInputs } from "@/utils/api/workflow/list/type";

// 获取工作流小仓储实例
const workflowStore = useWorkflowStore(pinia);

// 控制组件隐藏与显示
const modelValue = defineModel<boolean>(propTypes.bool.def(false));

// 组件实例
const flowForm = ref<FormInstance>();

// 表单验证规则
const flowRules = ref({});

// 表单数据
const formData = ref<StartWorkflowInputs>({});

// 定义传入参数
const props = defineProps({
  workflow: {
    type: Object as PropType<WorkflowDefinition>,
    required: true
  }
});

// 保存Loading效果状态
const isLoading = ref<boolean>(false);

// 定义刷新Emits
const emits = defineEmits<{
  (e: 'update:refresh'): void
}>();

// 刷新回调
const refresh = () => {
  emits('update:refresh');
};

// 关闭弹窗
const onClose = () => {
  modelValue.value = false;
};

// 保存
const onSavue = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) {
    return;
  }

  // 提交验证
  await formEl.validate(
    async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
      if (isValid) {
        try {
          isLoading.value = true;
          const data: StartWorkflowInput = {
            id: props.workflow.id,
            version: props.workflow.version,
            inputs: formData.value
          };
          await startAsync(data);
          // 关闭弹窗
          onClose();
          // 提示成功
          ElMessage.success('添加成功');
          // 刷新父组件
          refresh();
        } catch (error) {
          if (error) {
            let msg: string = (error as Error).message;
            if (msg) {
              ElMessage.error(msg);
            }
          }
        } finally {
          isLoading.value = false;
        }
      } else {
        console.log('error submit!', invalidFields);
      }
    }
  );
};

// 输入参数
const workflowInputs = computed(() => {
  let arr: any = [];
  props.workflow.inputs.forEach((element) => {
    element.forEach((obj) => {
      arr.push(...obj);
    });
  });
  return arr;
});

// 验证规则
const ruleDefinitions = computed(() => {
  let rdef: any = {};
  workflowStore.getRules.forEach((element: WorkFormComponentsRules) => {
    rdef[element.name] = element.value;
  });
  return rdef;
});

// 组件挂载完成
onMounted(() => {
  let rules: any = {};
  let form: any = {};
  workflowInputs.value.forEach((i: any) => {
    rules[i.name] = [];
    form[i.name] = null;
    if (i.rules && i.rules.length > 0) {
      i.rules.forEach((r: any) => {
        rules[i.name].push(ruleDefinitions.value[r]);
      });
    }
  });
  flowRules.value = { ...rules };
  formData.value = { ...form };
});

</script>

<style scoped lang="scss"></style>